package com.it.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : code1997
 * @date : 2021/9/9 22:46
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(HttpServletRequest request, Exception e) throws Exception {
        /*记录出现异常的url，异常信息*/
        logger.error("Request URL : {} , Exception : {}", request.getRequestURL(), e);

        /*当异常标注了状态码，就将这些异常交给springboot来及进行处理*/
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        ModelAndView modelAndView = new ModelAndView("error/error");
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.addObject("exception", e);
        return modelAndView;
    }

}
